package com.linwen.dataStructure.heap;

import java.util.Arrays;

/**
 * @author : linwen
 * @date : 11:16 下午 2020/11/12
 */
public class MyHeap {
    /**
     * 上浮
     * @param array
     */
    public static void upAdjust(int[] array){
        int childIndex = array.length-1;
        int parentIndex = (childIndex-1)/2;
        int temp = array[childIndex];
        while (childIndex>0 && temp<array[parentIndex]){
            array[childIndex] = array[parentIndex];
            childIndex = parentIndex;
            parentIndex = (parentIndex-1)/2;
        }
        array[childIndex] = temp;
    }

    /**
     * 下沉调整
     * @param arr
     * @param parentIndex
     * @param length
     */
    public static void downAdjust(int[] arr,int parentIndex,int length){
        int temp = arr[parentIndex];
        int childIndex = parentIndex*2+1;
        while (childIndex<length){
            if(childIndex+1<length && arr[childIndex+1]<arr[childIndex]){
                childIndex ++;
            }
            if(temp <= arr[childIndex]){
                break;
            }
            arr[parentIndex] = arr[childIndex];
            parentIndex = childIndex;
            childIndex = 2*childIndex+1;
        }
        arr[parentIndex] = temp;
    }
    public static void buildHeap(int[] array){
        for (int i=(array.length-2)/2;i>=0;i--){
            downAdjust(array,i,array.length);
        }
    }

    public static void main(String[] args) {
        int[] array = new int[]{1,3,2,6,5,7,8,9,10,0};
        upAdjust(array);
        System.out.println(Arrays.toString(array));

        array = new int[]{7,1,3,10,5,2,8,9,6};
        buildHeap(array);
        System.out.println(Arrays.toString(array));
    }
}
